package com.ahaoyou.compnent;

import com.ahaoyou.annotation.TableHandler;
import com.ahaoyou.utils.TableOperate;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class TableHandlerDispatcher implements BeanPostProcessor {

    private final Map<TableHandlerType, ITableHandler> handlerMap = new HashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clz = bean.getClass();
        TableHandler annotation = clz.getAnnotation(TableHandler.class);
        if (annotation != null) {
            String table = annotation.table();
            TableOperate operate = annotation.operate();
            handlerMap.put(new TableHandlerType(table, operate), ((ITableHandler) bean));
        }
        return bean;
    }

    /**
     * 执行对应的handler方法
     *
     * @param handlerType
     * @param json
     */
    public void dispatch(TableHandlerType handlerType, JSONObject json) {
        ITableHandler iHandler = handlerMap.get(handlerType);
        if (iHandler != null) {
            log.info("分派数据:{}", json);
            JSONObject table = json.getJSONArray("data").getJSONObject(0), old = null;
            if (handlerType.getOperate() == TableOperate.UPDATE) {
                old = json.getJSONArray("old").getJSONObject(0);
            }
            iHandler.handler(table, old);
        } else {
            log.warn("{}未找到实例处理,数据:{}", handlerType, json);
        }
    }


}
